﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using RBAC.LuFang.Domin.Services;
using RBAC.LuFang.Domin.Services.TraceabilityService;
using RBAC.LuFang.Repository.lmpl;
using RBAC.LuFang.Repository.lnterface;
using System.Text;

namespace RBAC.LuFang.API.Extensions
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// this 扩展预防
        /// string 被扩展的类型
        /// </summary>
        /// <param name="para">扩展方法传入的值</param>
        /// <returns></returns>
        public static int ToInt(this string para)
        {
            int result = 0;
            if(int.TryParse(para, out result))//true 类型转换成功
            {
                return result;
            }
            else
            {
                return -9999;
            }
            
        }

        public static string  Tosubstring(this string para)
        {
            return para.Substring(6, 8);


        }

        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddServices(this IServiceCollection services)
        {
            services.AddScoped<IUserService, UserService>();//用户服务层
            services.AddScoped<IRoleService, RoleService>();//角色服务层
            services.AddScoped<IMenuService, MenuService>();//菜单服务层
            services.AddScoped<IRoleMenuService, RoleMenuService>();//角色菜单服务层
            services.AddScoped<ILeaveapplicationService, LeaveapplicationService>();//请假服务层
            services.AddScoped<IGoodsService, GoodsService>();//商品服务层
            services.AddScoped<IslaughterService, slaughterService>();//屠宰服务层
            services.AddScoped<IdeepprocessingService, deepprocessingService>();//深加工服务层

            services.AddScoped<IUserRepository, UserRepository>();//用户接口
            services.AddScoped<IProvincesRepository, ProvincesRepository>();//省接口
            services.AddScoped<ITheCityRepository, TheCityRepository>();//市接口
            services.AddScoped<ICountyRepository, CountyRepository>();//县接口
            services.AddScoped<IRoleRepository, RoleRepository>();//角色接口
            services.AddScoped<IUserRoleRepository, UserRoleRepository>();//用户角色接口
            services.AddScoped<IMenuRepository, MenuRepository>();//菜单接口
            services.AddScoped<IRoleMenuRepository, RoleMenuRepository>();//角色菜单接口
            services.AddScoped<ILeaveapplicationRepository, LeaveapplicationRepository>();//请假接口
            services.AddScoped<IGoodsRepository, GoodsRepository>();//商品接口
            services.AddScoped<IimgesRepository, imgesRepository>();//照片接口
            services.AddScoped<IBreedInfoRepository, BreedInfoRepository>();//养殖接口
            services.AddScoped<IhealthRepository, healthRepository>();//保健接口
            services.AddScoped<IEnterpriseRepository, EnterpriseRepository>();//企业接口
            services.AddScoped<IslaughterRepository, slaughterRepository>();//屠宰接口
            services.AddScoped<IdeepprocessingRepository, deepprocessingRepository>();//深加工接口
            return services;
        }
        /// <summary>
        /// 数据库注入
        /// </summary>
        /// <typeparam name="TDContext"></typeparam>
        /// <param name="service"></param>
        /// <param name="connectionStrings"></param>
        /// <param name="enableSqlLog"></param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextService<TDContext>(this IServiceCollection service, string? connectionStrings, bool enableSqlLog) where TDContext : DbContext
        {
            return service.AddDbContext<TDContext>(builder =>
            {
                builder.UseSqlServer(connectionStrings, action =>
                {
                    action.EnableRetryOnFailure(
                        maxRetryCount: 10,
                        maxRetryDelay: TimeSpan.FromSeconds(60),
                        errorNumbersToAdd: null
                        );
                }).EnableSensitiveDataLogging();
                if (enableSqlLog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure
                        .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                        .AddConsole();
                    }));
                }
            });
        }
        /// <summary>
        /// 注册JWT
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="builder"></param>
        public static void AddJWT(this IServiceCollection collection,WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                //取出私钥
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecreKey"]);
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    //验证发布者
                    ValidateIssuer = true,
                    ValidIssuer = builder.Configuration["Authentication:Issuer"],
                    //验证接收者
                    ValidateAudience = true,
                    ValidAudience = builder.Configuration["Authentication:Audience"],
                    //验证是否过期
                    ValidateLifetime = true,
                    //验证私钥
                    IssuerSigningKey=new SymmetricSecurityKey(secretByte)
                };
            });
        }




    }
}
